<template>
  <div class="page">
    <Header title="订单确认" :back="true" />
    <div class="conform">
      <div class="img_bg">
        <img
          style="width: 100%"
          src="/src/assets/images/index/scenic_bg.png"
          alt=""
        />
      </div>
      <div class="commodity_information">
        <div class="commodity_information_img_box">
          <div class="img_box">
            <template v-if="!loading">
              <van-image
                lazy-load
                width="100%"
                height="100%"
                :src="`${fileUrl}/${userlist?.scenicSpot?.coverImage}`"
                radius=".8rem"
              />
            </template>
            <van-skeleton v-else>
              <template #template>
                <div :style="{ display: 'flex', width: '100vw' }">
                  <van-skeleton-image
                    :style="{ width: '100%', height: '8.7rem' }"
                  />
                </div>
              </template>
            </van-skeleton>
          </div>
          <div class="round round_left" />
          <div class="round round_right" />
        </div>
        <div class="order_info">
          <template v-if="!loading">
            <div class="order_info_header">
              {{ userlist.scenicSpot?.scenicAreaName }}-{{
                userlist.productClassifica?.classificationName
              }}
            </div>
            <div class="order_info_time">
              <div
                v-if="userlist.goodsTickets?.refundType === 0"
                class="cancel"
              >
                <span>不可取消</span>
                <div class="line"></div>
              </div>
              <span class="order_info_time_list" v-if="userlist?.userTime"
                >使用时间：{{ userlist?.userTime }}</span
              >
              <span
                class="order_info_time_list"
                v-if="userlist.subscribe?.beginTime"
              >
                场次：{{ userlist.subscribe?.beginTime
                }}{{ userlist.subscribe?.endTime }}
              </span>
            </div>
          </template>
          <van-skeleton v-else>
            <template #template>
              <div :style="{ display: 'flex', width: '100%' }">
                <div :style="{ flex: 1 }">
                  <van-skeleton-paragraph row-width="60%" />
                  <van-skeleton-paragraph />
                </div>
              </div>
            </template>
          </van-skeleton>
        </div>
      </div>
      <div class="card_box">
        <template v-if="!loading">
          <div class="header">门票种类</div>
          <div class="card">
            <div class="type">
              <div class="type_name">
                {{ userlist.goodsTickets?.ticketName }}
              </div>
              <div class="type_number">
                <div>
                  <span class="price">
                    ￥
                    <span class="price_number">{{
                      userlist.goodsTickets?.marketPrice
                    }}</span>
                  </span>
                </div>
                <van-stepper
                  v-model="ticketNumber"
                  integer
                  @change="handelvaluenumber"
                  :max="stepperMax || 99"
                />
              </div>
            </div>
          </div>
        </template>
        <van-skeleton v-else>
          <template #template>
            <div
              :style="{ display: 'flex', width: '100%', margin: '0 1.5rem' }"
            >
              <div :style="{ flex: 1 }">
                <van-skeleton-paragraph row-width="60%" />
                <van-skeleton-paragraph />
              </div>
            </div>
          </template>
        </van-skeleton>
      </div>
      <div class="card_box">
        <template v-if="!loading">
          <div class="header">
            出行人(请选择
            <span style="color: var(--van-primary-color)">{{
              ticketNumber
            }}</span>
            位出行人)
          </div>
          <div class="card">
            <div class="passenger">
              <div class="passenger_header">
                <div class="name">{{ userlist.goodsTickets?.ticketName }}</div>
                <div class="add" @click="shaopeople">
                  <van-icon name="plus" />
                  添加
                </div>
              </div>
              <div class="passenger_list_box" v-show="matchedResults.length">
                <div class="list" v-for="item in matchedResults" :key="item.id">
                  <div>
                    <div class="name">{{ item.name }}</div>
                    <div class="id_card">
                      身份证：
                      {{ item.idCard }}
                    </div>
                  </div>
                  <img
                    class="close_img"
                    @click="handeldelinfo(item.id)"
                    src="../../assets/images/icons/Frame60@2x.png"
                    alt=""
                  />
                </div>
              </div>
              <van-field
                class="field"
                v-model="tel"
                label="联系电话"
                placeholder="请输入手机号"
                input-align="right"
                type="tel"
                @blur="handeljianc"
              />
            </div>
          </div>
        </template>
        <van-skeleton v-else>
          <template #template>
            <div
              :style="{ display: 'flex', width: '100%', margin: '0 1.5rem' }"
            >
              <div :style="{ flex: 1 }">
                <van-skeleton-paragraph row-width="60%" />
                <van-skeleton-paragraph />
                <van-skeleton-paragraph />
                <van-skeleton-paragraph />
              </div>
            </div>
          </template>
        </van-skeleton>
      </div>
    </div>
    <div class="bottom_pay">
      <div class="bottom_pay_content">
        <template v-if="!loading">
          <div class="pay_button" @click="handelpay">支付</div>
          <div class="price_box">
            应付金额：
            <span class="price">
              ￥
              <span class="number">
                {{ ticketNumber * userlist.goodsTickets?.marketPrice || '' }}
              </span>
            </span>
          </div>
        </template>
        <van-skeleton v-else>
          <template #template>
            <div :style="{ display: 'flex', width: '50vw', margin: 'auto' }">
              <div :style="{ flex: 1 }">
                <van-skeleton-paragraph />
                <van-skeleton-paragraph />
              </div>
            </div>
          </template>
        </van-skeleton>
      </div>
    </div>
    <Choicetraveler
      v-if="listpersons"
      @onSelect="onSelect"
      :showPopup="show"
      @closePopup="closePopup"
      :listpersons="listpersons"
      :valuenumber="ticketNumber"
      :selectList="matchedResults"
    />
  </div>
</template>
<script setup>
import { ref, toRaw, onActivated } from 'vue'
import { showToast } from 'vant'
import { onBeforeRouteLeave, useRoute } from 'vue-router'
import Header from '@/components/header/Header.vue'
import Choicetraveler from '@/components/choicetraveler/Choicetraveler.vue'
import { showLoadingToast, closeToast } from 'vant'

defineOptions({
  name: 'scenicOrder',
})

const fileUrl = import.meta.env.VITE_FILE_URL

onBeforeRouteLeave((to, from) => {
  const needSaveRoute = ['addApedestrian', 'pedestrianedit']
  determineNeedSaveKeepALive(to, from, needSaveRoute, 'scenicOrder')
})

const route = useRoute()
const userlist = ref([])
import api from '@/api/index.js'
import pay from '@/utils/pay.js'
import { isValidPhoneNumber } from '@/utils/index'
import { determineNeedSaveKeepALive } from '@/utils/routerKeepALive.js'

const ticketNumber = ref(0)
if (Number(route?.query?.vanum)) {
  ticketNumber.value = Number(route.query.vanum)
}

let data = route?.query?.dateS
let scenicId = route?.query?.scenicId //景点id
let productid = route?.query?.productid //商品id
let ticketTypes = route?.query?.ticketTypes //分类id
let sessionid = route?.query?.sessionid //场次id
const stepperMax = ref(0)
if (route?.query?.stepperMax) {
  stepperMax.value = Number(route?.query?.stepperMax)
}

const tel = ref(null)
const listpersons = ref([])
const idCardArray = ref([])

const show = ref(false)
const selectedItems = ref([])
const closePopup = () => {
  show.value = false
}
const matchedResults = ref([])
// const selectedPassengerList = ref([])
const onSelect = (val) => {
  matchedResults.value = val
  //   selectedPassengerList.value = val
  idCardArray.value = toRaw(matchedResults.value).map((item) => item.id)
}

// 添加出行人
function handelcx(key) {
  const newArrayOfMatchedItems = toRaw(listpersons.value).filter(
    (item) => item.id === key
  )
  // 检查是否已存在匹配项
  const existingIndex = matchedResults.value.findIndex(
    (item) => item.id === key
  )
  if (existingIndex !== -1) {
    // 如果匹配项已存在，从matchedResults中删除它
    matchedResults.value.splice(existingIndex, 1)
  } else {
    // 否则，将新的匹配结果与之前的匹配结果合并到matchedResults数组中
    matchedResults.value.push(...newArrayOfMatchedItems)
  }
  idCardArray.value = toRaw(matchedResults.value).map((item) => item.id)
  // if (isSelected(key)) {
  //     // 如果当前项已经选定，再次点击时取消选定
  //     selectedItems.value = selectedItems.value.filter(item => item !== key);
  // } else {
  //     // 否则，选定当前项
  //     selectedItems.value.push(key);
  // }

  // router.push({ path: '/pedestrianmanagement' })
}
// 回传出行人信息

function shaopeople() {
  show.value = true
}

function handeldelinfo(id) {
  // handelcx(id);
  matchedResults.value = matchedResults.value?.filter((item) => item.id !== id)
  idCardArray.value = toRaw(matchedResults.value).map((item) => item.id)
}
const isSelected = (key) => {
  return selectedItems.value.includes(key)
}

const handelitem = (key) => {
  handelcx(key) // 在条件满足时执行
}

function handelvaluenumber(val) {
  if (val == stepperMax.value) {
    showToast(`限购${stepperMax.value}`)
  }
}

// 获取出行人列表
function getapedestrianlist() {
  api
    .getapedestrian()
    .then((res) => {
      listpersons.value = res.data
    })
    .finally(() => {})
}
onActivated(() => {
  getapedestrianlist()
})
getapedestrianlist()
// 更具多个id 预订不同景点
const loading = ref(false)
function geijdlist() {
  loading.value = true
  const params = {
    businessId: productid, //商品id
    frequencyId: sessionid, //场次id
    goodsKindsId: ticketTypes, //分类id
    scenicAreaId: scenicId, //景点id
    useTime: data,
  }

  api
    .getReserveTickets(params)
    .then((res) => {
      userlist.value = res.data
    })
    .finally(() => {
      loading.value = false
    })
}
geijdlist()

// 创建订单
function handelpay() {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  })
  const data = {
    goodsDto: {
      buyCount: ticketNumber.value,
      frequencyId: sessionid,
      idCardIds: toRaw(idCardArray.value),
      skuId: productid,
      useTime: userlist.value.userTime,
    },
    phone: tel.value,
  }

  if (ticketNumber.value == idCardArray.value.length) {
    api.orderpaymentsave(data).then((res) => {
      if (res.code == 200 && res.data != null && res.success == true) {
        // pay.getPayld({ orderNumber: res.data })
        _getIsCanPay(res.data)
      }
    })
  } else if (tel.value && truelist.value == 1) {
    api.orderpaymentsave(data).then((res) => {
      if (res.code == 200 && res.data != null && res.success == true) {
        // pay.getPayld({ orderNumber: res.data })
        _getIsCanPay(res.data)
      }
    })
  } else {
    if (ticketNumber.value != idCardArray.value.length) {
      showToast(`请选择${ticketNumber.value}位出行人`)
    }
    if (truelist.value == 2) {
      showToast('请输入正确手机号')
    }
  }
}

const _getIsCanPay = (orderNumber) => {
  api.getIsCanPay({ orderNumber }).then((res) => {
    if (res.code === 200 || res.code === '200') {
      closeToast()
      pay.getPayld({ orderNumber })
    }
  })
}
const truelist = ref()
// 检查手机号
function handeljianc() {
  if (tel.value) {
    if (isValidPhoneNumber(tel.value)) {
      truelist.value = 1
      return true
    } else {
      truelist.value = 2
      tel.value = ''
      showToast('请输入正确手机号')
    }
  }
}
</script>

<style lang="scss" scoped>
:deep(.van-skeleton) {
  padding: 0;
}
:deep(.van-cell) {
  padding: 1rem;
}
:deep(.van-field__control) {
  font-size: 1.4rem;
  color: #333333;
}
:deep(.van-stepper__input) {
  width: 5rem;
  border-radius: 5px;
}
:deep(.van-stepper__plus) {
  border-radius: 5px;
}
:deep(.vvan-image__imgs) {
  object-fit: cover;
}
.page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  .conform {
    flex: 1;
    position: relative;
    z-index: 1;
    height: 100%;
    overflow-y: auto;
    background-color: #f9f8f3;
    .img_bg {
      position: absolute;
      z-index: -1;
      top: 0;
      left: 0;
      width: 100%;
      height: 10vh;
    }
    .commodity_information {
      margin: 2.4rem 1.5rem 1.5rem 1.5rem;
      border-radius: 1rem;
      overflow: hidden;
      .commodity_information_img_box {
        position: relative;
        background: #ffffff;
        padding: 0 1.5rem;
        .img_box {
          height: 8.7rem;
          padding: 1.5rem 0;
          border-bottom: 1px dashed #eeeeee;
          :deep(.van-image__img) {
            object-fit: cover;
          }
        }
        .round {
          position: absolute;
          bottom: 0;
          width: 2.4rem;
          height: 2rem;
          background-color: #f9f8f3;
          border-radius: 50%;
        }
        .round_left {
          left: 0;
          transform: translateX(-50%) translateY(50%);
        }
        .round_right {
          right: 0;
          transform: translateX(50%) translateY(50%);
        }
      }
      .order_info {
        background: #ffffff;
        padding: 1.2rem 1.5rem 1.5rem 1.5rem;
        .order_info_header {
          font-size: 1.8rem;
          font-weight: bold;
          color: #333333;
          line-height: 2.5rem;
        }
        .order_info_time {
          display: flex;
          flex-wrap: wrap;
          margin-top: 0.6rem;
          font-size: 1.4rem;
          color: #999999;
          line-height: 2rem;
          .cancel {
            display: flex;
            align-items: center;
            font-size: 1.4rem;
            font-weight: normal;
            color: #999999;
            .line {
              width: 0.1rem;
              height: 1.4rem;
              background: #d9d9d9;
              margin: 0 0.5rem;
            }
          }
          .order_info_time_list {
            margin-right: 1rem;
          }
        }
      }
    }
    .card_box {
      margin-bottom: 1.5rem;
      .header {
        font-size: 1.4rem;
        font-weight: normal;
        color: #999999;
        margin: 0 1.5rem 1rem 1.5rem;
      }
      .card {
        background: #fffffc;
        box-shadow: 0 0.7rem 1.5rem 0 rgba(54, 141, 88, 0.05);
        border-radius: 1rem;
        margin: 0 1.5rem;
        padding: 1.9rem 1.5rem;
        .type {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .type_name {
            font-size: 1.6rem;
            font-weight: bold;
            color: #333333;
          }
          .type_number {
            display: flex;
            align-items: center;
            .price {
              font-size: 1.4rem;
              font-family: Alibaba PuHuiTi 2-75 SemiBold, Alibaba PuHuiTi 20;
              font-weight: bold;
              color: #ed6316;
              padding-right: 1rem;
              .price_number {
                font-size: 1.8rem;
              }
            }
          }
        }
      }
      .passenger {
        .passenger_header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .name {
            font-size: 1.6rem;
            font-weight: bold;
            color: #333333;
          }
          .add {
            height: 3rem;
            line-height: 3rem;
            background: rgba(0, 0, 0, 0.05);
            border-radius: 0.5rem;
            padding: 0 1.5rem;
          }
          .add:active {
            opacity: 0.5;
          }
        }
        .passenger_list_box {
          margin-top: 1.9rem;
          .list {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1rem;
            background: rgba(79, 172, 145, 0.05);
            .name {
              font-size: 1.4rem;
              color: #333333;
              line-height: 2rem;
              font-weight: bold;
            }
            .id_card {
              font-size: 1.2rem;
              color: #666666;
              line-height: 1.4rem;
            }
            .close_img {
              width: 2.4rem;
              height: 2.4rem;
            }
          }
        }
        .field {
          background: rgba(79, 172, 145, 0.05);
          margin-top: 1.5rem;
          border-radius: 0.5rem;
        }
      }
    }
  }
  .bottom_pay {
    z-index: 1;
    height: 9rem;
    background-color: #ffffff;
    .bottom_pay_content {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
      padding: 1rem 2rem 0 0;
      box-sizing: border-box;
    }
    .pay_button {
      height: 3.8rem;
      line-height: 3.8rem;
      background: var(--van-primary-color);
      border-radius: 0.5rem;
      opacity: 1;
      font-size: 1.6rem;
      color: #ffffff;
      padding: 0 3rem;
      margin-left: 1rem;
      white-space: nowrap;
    }
    .pay_button:active {
      background-color: var(--van-primary-button-active-color);
    }
    .price_box {
      display: flex;
      align-items: center;
      font-size: 1.4rem;
      color: #999999;
      .price {
        font-size: 1.4rem;
        color: #ed6316;
        line-height: 1.6rem;
        font-weight: bold;
        .number {
          font-size: 2.2rem;
          font-weight: bold;
          color: #ed6316;
          line-height: 2.6rem;
        }
      }
    }
  }
}
</style>
